package org.dromara.tearoom.service.impl;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.dev33.satoken.jwt.SaJwtUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.tearoom.domain.TerUser;
import org.dromara.tearoom.domain.bo.TerUserBo;
import org.dromara.tearoom.domain.bo.TerUserCountTotalBo;
import org.dromara.tearoom.domain.vo.TerUserDayVo;
import org.dromara.tearoom.domain.vo.TerUserVo;
import org.dromara.tearoom.domain.vo.WxPayProperties;
import org.dromara.tearoom.mapper.TerUserMapper;
import org.dromara.tearoom.service.ITerUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户Service业务层处理
 *
 * @author xch
 * @date 2025-03-29
 */
@RequiredArgsConstructor
@EnableConfigurationProperties(WxPayProperties.class)
@Service
@Slf4j
public class TerUserServiceImpl implements ITerUserService {
    private final TerUserMapper baseMapper;
    private final WxMaService wxMaService;

    @Value("${sa-token.jwt-secret-key}")
    private String jwtSecret;



    public TerUserVo login(String code){
        TerUserVo vo =  new TerUserVo();
        WxMaJscode2SessionResult sessionResult = null;
        try {
            sessionResult = wxMaService.getUserService().getSessionInfo(code);
        } catch (WxErrorException e) {
            throw new ServiceException(e.getError().getErrorMsg());
        }
        if (ObjectUtil.isEmpty(sessionResult) || StringUtils.isBlank(sessionResult.getOpenid())) {
            log.error("微信小程序登录失败code:{}",code);
            throw new ServiceException("微信小程序登录失败");
        }
        log.info("微信小程序登录成功:{}", sessionResult);
        // 3. 处理用户信息(如绑定或创建用户)
        TerUserBo bo = new TerUserBo();
        bo.setOpenId(sessionResult.getOpenid());
        LambdaQueryWrapper<TerUser> lqw = buildQueryWrapper(bo);
        TerUserVo user= baseMapper.selectVoOne(lqw);
        if(ObjectUtil.isNotEmpty(user)){
            //新增用户信息
            bo.setWechatNo(sessionResult.getUnionid());
            insertByBo(bo);
        }
        // 返回登录凭证（如 JWT）
        String jwtToken = generateJwtToken(vo);
        vo.setJwtToken(jwtToken);
        return vo;
    }


    private  String generateJwtToken(TerUserVo vo){
        Map<String,Object> model = new HashMap<>();
        model.put("role", "user");
        model.put("loginId",vo.getOpenId());
        String token = SaJwtUtil.createToken(model,jwtSecret);

        return token;
    }

    /**
     * 新增用户
     *
     * @param bo 用户
     * @return 是否新增成功
     */

    public Boolean insertByBo(TerUserBo bo) {
        TerUser add = MapstructUtils.convert(bo, TerUser.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }



    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TerUser entity){
        //TODO 做一些数据校验,如唯一约束
    }

    public TerUserDayVo queryUserCount(TerUserCountTotalBo tbo) {
        if(tbo.getDaynum()!=null&&tbo.getDaynum()==0){
           return baseMapper.selectUserTaDayVo();
        }else if(tbo.getStart()!=null&&tbo.getEnd()!=null){
            return baseMapper.selectUserStarAndEnd(tbo.getStart(),tbo.getEnd());
        }else{
            return baseMapper.selectUserMonth(tbo.getDaynum());
        }
    }

    /**
     * 查询用户管理
     *
     * @param id 主键
     * @return 用户管理
     */
    @Override
    public TerUserVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询用户管理列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 用户管理分页列表
     */
    @Override
    public TableDataInfo<TerUserVo> queryPageList(TerUserBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TerUser> lqw = buildQueryWrapper(bo);
        Page<TerUserVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的用户管理列表
     *
     * @param bo 查询条件
     * @return 用户管理列表
     */
    @Override
    public List<TerUserVo> queryList(TerUserBo bo) {
        LambdaQueryWrapper<TerUser> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TerUser> buildQueryWrapper(TerUserBo bo) {
        LambdaQueryWrapper<TerUser> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(TerUser::getId);
        lqw.like(StringUtils.isNotBlank(bo.getNickname()), TerUser::getNickname, bo.getNickname());
        lqw.eq(StringUtils.isNotBlank(bo.getWechatNo()), TerUser::getWechatNo, bo.getWechatNo());
        lqw.eq(StringUtils.isNotBlank(bo.getOpenId()), TerUser::getOpenId, bo.getOpenId());
        lqw.eq(StringUtils.isNotBlank(bo.getAvatar()), TerUser::getAvatar, bo.getAvatar());
        lqw.eq(StringUtils.isNotBlank(bo.getMobile()), TerUser::getMobile, bo.getMobile());
        lqw.eq(bo.getLastLoginAt() != null, TerUser::getLastLoginAt, bo.getLastLoginAt());
        lqw.eq(bo.getStatus() != null, TerUser::getStatus, bo.getStatus());
        return lqw;
    }



    /**
     * 修改用户管理
     *
     * @param bo 用户管理
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(TerUserBo bo) {
        TerUser update = MapstructUtils.convert(bo, TerUser.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 校验并批量删除用户管理信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
